package com.imist.demo3;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 后处理Bean，需要在xml中配置bean
 * 可以对类进行增强
 */
public class MyBeanPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String s) throws BeansException {
        System.out.println("第五步：初始化前方法...");
        return bean;
    }

    /**
     * @param bean 实例化对象
     * @param beanName 配置的区分Bean对象唯一ID或者name
     * @return
     * @throws BeansException
     */
    public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
        System.out.println("第八步：初始化后方法...");
        if ("userDao".equals(beanName)){
            Object proxy = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    //对保存操作进行增强，添加一个权限检查
                    if ("save".equals(method.getName())){
                        System.out.println("权限检查------");
                        return method.invoke(bean,args);
                    }
                    //其他操作正常调用
                    return  method.invoke(bean,args);
                }
            });
            //这里必须返回 代理对象，不然无法增强
            return proxy;
        }
        return bean;
    }
}
